package Adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.qb.devserv.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private Context mCtx;
    private JSONArray mData;
    private List<Boolean> isClicks;
    private int i = 0;

    public ItemAdapter(Context ctx, JSONArray data) {
        mCtx = ctx;
        mData = data;
        isClicks = new ArrayList<>();
        for (int i = 0; i < data.length(); i++) {
            isClicks.add(false);
            if (i == 0) {
                isClicks.set(0, true);
            }
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_item_layout, parent, false);
        return new MHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        MHolder mHolder = (MHolder) holder;
        try {
            JSONObject o = new JSONObject(mData.get(position).toString());
            String k = o.getString("key");
            mHolder.itemKey.setText(k);
            mHolder.itemValue.setText(o.getString("value"));
            if (k.equals("title")) {
                mHolder.llItem.setBackgroundColor(Color.parseColor("#EEEEEE"));
                mHolder.itemKey.setVisibility(View.GONE);
                mHolder.itemValue.setTextSize(18);
            } else {
                mHolder.llItem.setBackgroundColor(Color.parseColor("#FFFFFF"));
                mHolder.itemKey.setVisibility(View.VISIBLE);
                mHolder.itemValue.setTextSize(16);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return mData.length();
    }

    public class MHolder extends RecyclerView.ViewHolder {
        public LinearLayout llItem;
        public TextView itemKey,itemValue;
        public MHolder(View v) {
            super(v);
            llItem = v.findViewById(R.id.ll_item);
            itemKey = v.findViewById(R.id.tv_item_key);
            itemValue = v.findViewById(R.id.tv_item_value);
        }
    }

    public void setData(int position) {
        this.i = position;
    }
}
